<template>
  <div class="dialog-form">
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      v-if="open"
      :title="title"
      center
      :visible="open"
      :modal="open"
      @close="close()"
      :close-on-click-modal="false"
      width="60%"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="是否管理员" v-if="admin">
          <el-radio-group @change="handleUserTypeChange()" v-model="form.userType" placeholder="请选择">
            <el-radio v-for="(dict, index) in adminOptions" :key="index" :label="dict.value">{{ dict.text }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="租户选择" prop="tenantCode" v-show="adminVisible">
          <el-select
            v-model="form.tenantCode"
            placeholder="请选择租户"
            class="common-select"
            :disabled="tenantCodeIsAble"
            @change="refreshRoleData()"
          >
            <el-option
              v-for="item in tenantOptions"
              :key="item.tenantCode"
              :label="item.tenantName"
              :value="item.tenantCode"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 机构选择组件 -->
        <el-form-item :label="this.lang('authority.userInfo.form.deptName')" prop="treeDeptIds" v-if="!adminVisible">
          <ht-dept-select-tree
            ref="deptTree"
            key="editUser"
            v-model="treeDeptIds"
            :radio="true"
            node-key="code"
            :tempTenantCode="form.tenantCode"
            @otherChangeChecked="treeChangeChecked"
          ></ht-dept-select-tree>
        </el-form-item>

        <el-form-item :label="this.lang('authority.userInfo.form.loginName')" prop="loginName">
          <el-input v-model="form.loginName" placeholder="请输入登录名称" :disabled="disabled"/>
        </el-form-item>

        <el-form-item :label="this.lang('authority.userInfo.form.userName')" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名"/>
        </el-form-item>

        <el-form-item v-if="!form.id" label="用户密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入用户密码" type="password" auto-complete="new-password"/>
        </el-form-item>

        <el-form-item :label="this.lang('authority.userInfo.form.phoneNumber')" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11"/>
        </el-form-item>

        <el-form-item label="Email" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="form.sex" placeholder="请选择">
            <el-radio v-for="(dict, index) in sexOptions" :key="index" :label="dict.value">{{ dict.text }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="this.lang('authority.userInfo.form.status')">
          <el-switch v-model="form.status" active-value="1" inactive-value="2"></el-switch>
        </el-form-item>

        <el-form-item label="岗位">
          <el-select v-model="form.postIds" placeholder="请选择岗位" clearable class="common-select">
            <el-option v-for="item in postOptions" :key="item.id" :label="item.postName"
                       :value="`${item.id}`"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="this.lang('authority.userInfo.form.role')" prop="roleIds" v-show="!adminVisible">
          <el-select v-model="form.roleIds" multiple placeholder="请选择角色" class="common-select">
            <el-option v-for="item in roleOptions" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <ht-extend-form
          ref="htExtendForm"
          v-if="extendParams"
          :extendParams="extendParams"
          :expandValueInfoMap="form.expandValueInfoMap"
          :dictReqFun="getDictReq"
          labelWidth = "100px"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("common.confirm") }}</el-button>
        <el-button @click="close">{{ $t("common.cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  updateUser,
  checkLoginName,
  checkEmail,
  checkPhone,
  getUserAndExtend,
} from "@/api/authority_app/user/userInfo";
import {rolesByUserId, userRolesByUserId, getMyTenants} from "@/api/authority_app/role/roleInfo";
import {searchPostByStatusVue, selectPostsByUserId} from "@/api/authority_app/post/postInfo";
import {mapGetters} from "vuex";
import Vue from "vue";
import {encrypt} from "@/utils/DES3";
import {getRandomSecretKey} from "@/utils";

export default {
  name: "userEditForm",
  components: {},
  computed: {
    ...mapGetters(["admin"]),
  },
  props: {
    extendParams: {
      type: Array,
      default: {},
    },
  },
  data() {
    // 表单校验
    var checkLoginNameUnique = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error(`${this.lang("authority.userInfo.rules.loginNameEmpty")}`));
      } else {
        let temp = _.clone(this.form);
        delete temp.password;
        checkLoginName(temp).then((response) => {
          var result = response.result;
          if (!result) {
            callback(new Error("登录名称已经存在"));
          } else {
            callback();
          }
        });
      }
    };
    var checkEmailUnique = (rule, value, callback) => {
      if (!value) {
        callback(new Error("邮箱不能为空"));
      } else {
        checkEmail({
          email: value,
          id: this.form.id,
        }).then((response) => {
          var result = response.result;
          if (!result) {
            callback(new Error("邮箱已经存在"));
          } else {
            callback();
          }
        });
      }
    };
    var checkPhoneUnique = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("手机号不能为空"));
      } else {
        let temp = _.clone(this.form);
        delete temp.password;
        checkPhone(temp).then((response) => {
          var result = response.result;
          if (!result) {
            callback(new Error("手机号已经存在"));
          } else {
            callback();
          }
        });
      }
    };
    let checkParent = (rule, value, callback) => {
      this.$nextTick(() => {
        if (!this.treeDeptIds) {
          callback(new Error("请选择上级组织"));
        } else {
          callback();
        }
      });
    };
    return {
      open: false,
      title: "",
      disabled: false,
      // 性别状态字典
      sexOptions: [],
      //是否管理员字典状态
      adminOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      //租户选项
      tenantOptions: [],
      treeDeptIds: "",
      checkedDeptIds: "",
      deptId: [],
      //管理员可见的组件
      adminVisible: false,
      tenantCodeIsAble: false,
      //用户的旧值
      originFormData: {},
      //用户数据的旧值，新值
      userDataList: [],
      form: {
        id: "",
        loginName: "",
        userName: "",
        phoneNumber: "",
        email: "",
        sex: "3",
        status: "0",
        password: "",
        deptId: [],
        postIds: [],
        roleIds: [],
        userType: "1",
        tenantCode: "",
        expandValueInfoMap: {},
        deptCode: ""
      },
      // 表单校验
      rules: {
        treeDeptIds: [
          {
            required: true,
            message: "请选择上级组织",
            trigger: "change",
            validator: checkParent,
          },
        ],
        loginName: [
          {
            required: !this.disabled,
            trigger: "blur",
            validator: checkLoginNameUnique,
          },
          {min: 2, max: 20, message: "长度为2~20位", trigger: "blur"},
        ],
        userName: [
          {required: true, message: "用户名不能为空", trigger: "blur"},
          {min: 2, max: 20, message: "长度为2~20位", trigger: "blur"},
        ],
        password: [{required: true, message: "用户密码不能为空", trigger: "blur"}],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
          {required: true, trigger: "blur", validator: checkEmailUnique},
          {min: 3, max: 100, message: "长度为3~100位", trigger: "blur"},
        ],
        phoneNumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
          {required: true, trigger: "blur", validator: checkPhoneUnique},
          {min: 11, max: 20, message: "长度为11~20位", trigger: "blur"},
        ],
        roleIds: [{required: true, message: "角色不能为空", trigger: "change"}],
      },
      deptTreeCheckedValues: [],
    };
  },
  created() {
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.result;
    });

    this.getDicts("user_type").then((response) => {
      this.adminOptions = response.result;
    });
  },
  methods: {
    getRolesByUserId(userId, deptId, tenantCode) {
      rolesByUserId(userId, deptId, tenantCode).then((response) => {
        this.roleOptions = response.result;
        this.$forceUpdate();
      });
    },

    getSearchPostByStatusVue() {
      searchPostByStatusVue().then((response) => {
        this.postOptions = response.result;
      });
    },

    refreshRoleData() {
      this.getRolesByUserId("", "", this.form.tenantCode);
    },
    getMyTenants() {
      getMyTenants().then((response) => {
        this.tenantOptions = response.result;
        if (this.tenantOptions.length == 1) {
          this.form.tenantCode = this.tenantOptions[0].tenantCode;
          this.tenantCodeIsAble = true;
        } else {
          this.tenantCodeIsAble = false;
        }
      });
    },

    handleUserTypeChange() {
      this.form.deptCode = "";
      this.checkedDeptIds = "";
      this.treeDeptIds = "";
      if (this.form.userType == "2") {
        //管理员
        this.adminVisible = true;
        this.form.roleIds = [];
        this.roleOptions = [];
        this.getMyTenants();
        this.rules.roleIds[0].required = false;
      } else {
        this.adminVisible = false;
        this.form.tenantCode = "";
        this.refreshRoleData();
        this.rules.roleIds[0].required = true;
      }
    },

    // 取消按钮
    close() {
      this.$refs.htExtendForm.clearInput();
      this.$emit("changeTypeInfoOpen", false);
      this.open = false;
      this.resetFormData();
    },

    /** 提交按钮 */
    // submitForm: function () {
    //   if (this.form.userType == 1 && this.$refs.deptTree) {
    //     this.treeChangeChecked(this.$refs.deptTree.getSelectDataList());
    //   }
    //   this.$refs["form"].validate((valid) => {
    //     console.log(this.form.roleIds);
    //     if (valid) {
    //       this.form.expandValueInfoMap = this.$refs.htExtendForm.getExtendParamsValue();
    //       this.form.deptId = this.checkedDeptIds; //.join(",");
    //       const data = _.cloneDeep(this.form);
    //       data["postIds"] = [`${this.form.postIds}`];
    //       if (this.form.id) {
    //         Vue.delete(data, "password");
    //         updateUser(data).then((response) => {
    //           this.msgSuccess("修改成功");
    //           this.close();
    //         });
    //       } else {
    //         if (data.password) {
    //           let secretKey = getRandomSecretKey();
    //           data.key = secretKey;
    //           data.password = encrypt(secretKey, data.password);
    //         }
    //         addUser(data).then((response) => {
    //           this.msgSuccess("新增成功");
    //           this.close();
    //         });
    //       }
    //     }
    //   });
    // },
    submitForm: function () {
      if (this.form.userType == 1 && this.$refs.deptTree) {
        this.treeChangeChecked(this.$refs.deptTree.getSelectDataList());
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.expandValueInfoMap = this.$refs.htExtendForm.getExtendParamsValue();
          this.form.deptId = this.checkedDeptIds; //.join(",");
          const data = _.cloneDeep(this.form);
          if (this.form.postIds) {
            data["postIds"] = [`${this.form.postIds}`];
          } else {
            data["postIds"] = [];
          }

          if (this.form.id) {
            Vue.delete(data, "password");
            this.originFormData["postIds"] = [`${this.originFormData.postIds}`];
            this.userDataList.push(this.originFormData, data);
            const dataList = _.cloneDeep(this.userDataList);
            updateUser(dataList).then((response) => {
              this.msgSuccess("操作成功，待审核");
              this.close();
            });
          } else {
            if (data.password) {
              let secretKey = getRandomSecretKey();
              data.key = secretKey;
              data.password = encrypt(secretKey, data.password);
            }
            addUser(data).then((response) => {
              this.msgSuccess("操作成功，待审核");
              this.close();
            });
          }
        }
      });
      this.userDataList = [];
    },
    getDictReq(dictCode) {
      return this.getDicts(dictCode);
    },
    getUserRolesByUserId(userId, deptId) {
      return userRolesByUserId(userId, deptId).then((response) => {
        if (response.result.length > 0) {
          let tempRoleIds = [];
          response.result.forEach((element) => {
            tempRoleIds.push(element.id);
          });
          this.$set(this.form, "roleIds", tempRoleIds);
          this.originFormData = {...this.form};
          // this.$set(this.originFormData, "deptNames", this.$refs.deptTree.getSelectDataList().map((x) => x.name).join(","));
        }
      });
    },
    getSelectPostsByUserId(userId) {
      return selectPostsByUserId(userId).then((response) => {
        if (response && response.result && response.result.length > 0) {
          this.$set(this.form, "postIds", response.result[0].id);
          this.originFormData = {...this.form};
          // this.$set(this.originFormData, "deptNames", this.$refs.deptTree.getSelectDataList().map((x) => x.name).join(","));
        }
      });
    },
    resetFormData() {
      this.$set(this, "form", {expandValueInfoMap: {}});
    },
    treeChangeChecked(res) {
      let selectTenantCode = res.map((x) => x.tenantCode).join(",");
      this.getRolesByUserId("", "", selectTenantCode);
      this.checkedDeptIds = res.map((x) => x.id).join(",");
      this.form.deptCode = res.map((x) => x.code).join(",")
    },
    show(id = "") {
      this.treeDeptIds = "";
      if (id) {
        this.disabled = true;
        this.deptId = [];
        this.curUserId = id;

        getUserAndExtend(id).then((response) => {

          this.$set(this, "form", {
            id: response.result.id,
            loginName: response.result.loginName,
            userName: response.result.userName,
            phoneNumber: response.result.phoneNumber,
            email: response.result.email,
            sex: response.result.sex + "",
            userType: response.result.userType + "",
            status: response.result.status + "",
            expandValueInfoMap: response.result.expandValueInfoMap,
            password: "",
            tenantCode: response.result.tenantCode,
            deptId: response.result.deptId,
            deptCode: response.result.deptCode
          });
          this.deptId = response.result.deptId;
          this.checkedDeptIds = response.result.deptId;
          let tenantCode = response.result.tenantCode;
          this.open = true;
          this.title = "修改用户";
          this.treeDeptIds = response.result.deptCode;
          this.getUserRolesByUserId(id, this.deptId);
          this.getSelectPostsByUserId(id);
          this.adminVisible = response.result.userType == "2";
          if (response.result.userType == 2) {
            this.rules.roleIds[0].required = false;
          } else {
            this.rules.roleIds[0].required = true;
            this.refreshRoleData();
          }

          getMyTenants().then((response) => {
            this.tenantOptions = response.result;
            if (this.tenantOptions.length == 1) {
              this.form.tenantCode = this.tenantOptions[0].tenantCode;
              this.tenantCodeIsAble = true;
              this.getRolesByUserId("", "", this.form.tenantCode);
            } else {
              this.tenantCodeIsAble = false;
              this.getRolesByUserId("", "", tenantCode);
            }
          });
        });
      } else {
        this.$set(this.form, "id", id);
        this.disabled = false;
        this.curUserId = "";
        this.deptId = [];
        this.form.status = "1";
        this.open = true;
        this.form.userType = "1";
        this.adminVisible = false;
        this.tenantCodeIsAble = false;
        this.title = "添加用户";
        getMyTenants().then((response) => {
          this.tenantOptions = response.result;
          if (this.tenantOptions.length == 1) {
            this.form.tenantCode = this.tenantOptions[0].tenantCode;
            this.tenantCodeIsAble = true;
            this.getRolesByUserId("", "", this.form.tenantCode);
          } else {
            this.tenantCodeIsAble = false;
            this.getRolesByUserId("", "", "");
          }
        });
        if (this.form.userType == 2) {
          this.rules.roleIds[0].required = false;
        } else {
          this.rules.roleIds[0].required = true;
          this.refreshRoleData();
        }
      }
      this.$nextTick((res) => {
        this.$refs.htExtendForm.genData();
      });
      this.getSearchPostByStatusVue();
      this.open = true;
    },
  },
};
</script>
